package com.fenqing.leetcode.code.t300_400;

import com.fenqing.annotations.Execute;
import com.fenqing.core.Topic;

import java.util.Stack;

/**
 * @author fenqing
 */
public class Topic394 extends Topic {
    /**
     * 构造器
     *
     * @param input 输入
     */
    public Topic394(String input) {
        super(input);
    }

    @Execute
    public String decodeString(String s) {
        char[] chars = s.toCharArray();
        Stack<String> stack = new Stack<>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            char ch = chars[i];
            if (isNumber(ch)) {
                sb.setLength(0);
                sb.append(ch);
                int end = i + 1;
                while (end < chars.length && isNumber(chars[end])) {
                    sb.append(chars[end]);
                    end++;
                }
                i = end - 1;
                stack.push(sb.toString());
            } else if (ch == '[') {
                stack.push("[");
            } else if (ch == ']') {
                sb.setLength(0);
                String temp = null;
                while (true){
                    String pop = stack.pop();
                    if (pop.equals("[")){
                        break;
                    }
                    sb.insert(0, pop);
                }
                temp = sb.toString();
                int num = Integer.parseInt(stack.pop());
                sb.setLength(0);
                for (int integer = 0; integer < num; integer++) {
                    sb.append(temp);
                }
                stack.push(sb.toString());
            } else {
                sb.setLength(0);
                sb.append(ch);
                int end = i + 1;
                while (end < chars.length && !isNumber(chars[end]) && chars[end] != '[' && chars[end] != ']'){
                    sb.append(chars[end]);
                    end++;
                }
                stack.push(sb.toString());
                i = end - 1;
            }
        }
        return String.join("", stack);
    }

    private boolean isNumber(char ch) {
        return ch >= '0' && ch <= '9';
    }

    public static void main(String[] args) {
        Topic394 topic394 = new Topic394("3[z]2[2[y]pq4[2[jk]e1[f]]]ef");
        String run = topic394.run();
        System.out.println(run);
    }
}
